﻿Imports System
Imports System.Security.Cryptography
Imports System.ServiceModel
Imports System.ServiceModel.Channels
Imports System.ServiceModel.Dispatcher
Imports System.Text
Imports System.Text.RegularExpressions

Namespace Services.Amazon
    Public Class AmazonSigningMessageInspector
        Implements IClientMessageInspector
        Private accessKeyId As String = ""
        Private secretKey As String = ""

        Public Sub New(ByVal accessKeyId As String, ByVal secretKey As String)
            Me.accessKeyId = accessKeyId
            Me.secretKey = secretKey
        End Sub

        Public Function BeforeSendRequest(ByRef request As Message, ByVal channel As IClientChannel) As Object Implements IClientMessageInspector.BeforeSendRequest
            ' prepare the data to sign
            Dim operation As String = Regex.Match(request.Headers.Action, "[^/]+$").ToString()
            Dim now As DateTime = DateTime.UtcNow
            Dim timestamp As String = now.ToString("yyyy-MM-ddTHH:mm:ssZ")
            Dim signMe As String = operation & timestamp
            Dim bytesToSign As Byte() = Encoding.UTF8.GetBytes(signMe)

            ' sign the data
            Dim secretKeyBytes As Byte() = Encoding.UTF8.GetBytes(secretKey)
            Dim hmacSha256 As HMAC = New HMACSHA256(secretKeyBytes)
            Dim hashBytes As Byte() = hmacSha256.ComputeHash(bytesToSign)
            Dim signature As String = Convert.ToBase64String(hashBytes)

            ' add the signature information to the request headers
            request.Headers.Add(New AmazonHeader("AWSAccessKeyId", accessKeyId))
            request.Headers.Add(New AmazonHeader("Timestamp", timestamp))
            request.Headers.Add(New AmazonHeader("Signature", signature))

            Return Nothing
        End Function

        Public Sub AfterReceiveReply(ByRef reply As Message, ByVal correlationState As Object) Implements IClientMessageInspector.AfterReceiveReply
        End Sub
    End Class
End Namespace
